package com.my.interview.nio_socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;

public class HttpServer {

    public static void main(String[] args) {

        try{
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.socket().bind(new InetSocketAddress(8888));
            //设置为非阻塞模式
            ssc.configureBlocking(false);
            //为ssc注册选择器
            Selector selector = Selector.open();
            ssc.register(selector, SelectionKey.OP_ACCEPT);
            //创建新的处理器
            while (true){
                //等待请求，每次等待阻塞3s,查过3s后继续向下运行，如果传入0或者不传参将一直阻塞
                if(selector.select(3000) == 0){
                    System.out.println("等待请求超时.....");
                    continue;
                }
                System.out.println("请求处理中==========");
                Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
                while (keyIterator.hasNext()){
                    SelectionKey key = keyIterator.next();
                     new Thread(new HttpHandler(key)).run();
                    //处理完后，从待处理的SelectionKey迭代器中一处当前所使用的key
                    keyIterator.remove();
                }
            }
        }catch (IOException e){

        }


    }


    private static class HttpHandler implements Runnable{

        private int bufferSize = 1024;
        private String localCharset = "UTF-8";
        private SelectionKey key;


        public HttpHandler(SelectionKey key) {
            this.key = key;
        }

        public void handleAccept() throws IOException{

            SocketChannel sc = ((ServerSocketChannel) key.channel()).accept();
            sc.configureBlocking(false);
            sc.register(key.selector(),SelectionKey.OP_READ, ByteBuffer.allocate(bufferSize));
        }

        public void handleRead() throws IOException{

            //获取channel
            SocketChannel sc = (SocketChannel) key.channel();

            ByteBuffer byteBuffer = (ByteBuffer) key.attachment();
            byteBuffer.clear();
            if(sc.read(byteBuffer) == -1){
                sc.close();
            }else{
                //将buffer转化为读状态
                byteBuffer.flip();
                String receivedString = Charset.forName(localCharset).newDecoder().decode(byteBuffer).toString();
                System.out.println("received data from client: " + receivedString);
                String [] requestMessage = receivedString.split("\r\n");
                for(String s: requestMessage){
                    System.out.println(s);
                    if(s.isEmpty()){
                        break;
                    }
                }
                //控制台打印首行信息
                String [] firstLine = requestMessage[0].split(" ");
                System.out.println();
                System.out.println("Method:\t" + firstLine[0]);
                System.out.println("url:\t" + firstLine[1]);
                System.out.println("HTTP Version:\t" + firstLine[2]);

                //返回数据给客户端
                StringBuilder sb = new StringBuilder();
                sb.append("HTTP/1/1 200 OK\r\n");
                sb.append("Content-Type: text.html;charset=" + localCharset + "\r\n");
                sb.append("\r\n");

                sb.append("<html><head><title>显示报文</title></head><body>");
                sb.append("接收到请求报文是：<br>");
                for(String s: requestMessage){
                    sb.append(s + "<br/>");
                }
                sb.append("</body></html>");
                byteBuffer = ByteBuffer.wrap(sb.toString().getBytes());
                sc.write(byteBuffer);
                //关闭socket
                sc.close();
            }
        }

        @Override
        public void run() {

            try{
                //接收到链接请求时
                if(key.isAcceptable()){
                    handleAccept();
                }
                //读数据
                if(key.isReadable()){
                    handleRead();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}
